<template>
    <AdminSkeleton :headerIsHeight="true">
        <template #header>
            <div class="params-form">
                <el-form :model="paramsForm" label-width="auto" :rules="rules" ref="formRef">
                    <div class="one-box">
                        <el-form-item label="检测完成开始日期:" size="small" prop="begindate">
                            <el-date-picker size="small" v-model="paramsForm.begindate" type="date" placeholder="请选择日期"
                                format="YYYY/MM/DD" value-format="YYYY-MM-DD" :value-on-clear="''" />
                        </el-form-item>
                        <el-form-item label="检测完成结束日期:" size="small" prop="enddate">
                            <el-date-picker size="small" v-model="paramsForm.enddate" type="date" placeholder="请选择日期"
                                format="YYYY/MM/DD" value-format="YYYY-MM-DD" :value-on-clear="''" />
                        </el-form-item>
                        <el-form-item label="设备描述:" size="small" label-width="70px">
                            <el-input v-model="paramsForm.description" size="small" style="width: 100px" />
                        </el-form-item>
                        <el-form-item size="small">
                            <el-checkbox v-model="paramsForm.noexists" label="无主控记录" size="small" />
                        </el-form-item>
                    </div>
                    <div class="two-box">
                        <el-form-item label="线路:" size="small" label-width="50px">
                            <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                                <el-select v-model="paramsForm.lines" clearable placeholder="可留空" size="small"
                                    style="width: 150px" multiple collapse-tags collapse-tags-tooltip
                                    @change="changeLines" @visible-change="getLines">
                                    <template #header>
                                        <el-checkbox v-model="lineCheckAll" :indeterminate="lineIndeterminate"
                                            @change="lineHandleCheckAll">
                                            全选
                                        </el-checkbox>
                                    </template>
                                    <el-option v-for="item in linesAndStationsArr" :label="item.label"
                                        :value="item.value" :key="item.value" />
                                </el-select>
                                <!-- <el-select v-model="paramsForm.line" clearable placeholder="可留空" size="small"
                                style="width: 150px" @change="changeLines" @visible-change="getLines">
                                <el-option v-for="item in linesAndStationsArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select> -->
                            </el-config-provider>
                        </el-form-item>
                        <el-form-item label="站点:" size="small" label-width="40px">
                            <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                                <el-select v-model="paramsForm.stations" multiple clearable collapse-tags
                                    collapse-tags-tooltip placeholder="可留空" size="small" style="width: 150px"
                                    @change="changeStations">
                                    <template #header>
                                        <el-checkbox v-model="stationCheckAll" :indeterminate="stationIndeterminate"
                                            @change="stationHandleCheckAll">
                                            全选
                                        </el-checkbox>
                                    </template>
                                    <el-option v-for="item in stationsArr" :label="item.label" :value="item.value"
                                        :key="item.value" />
                                </el-select>
                            </el-config-provider>
                        </el-form-item>
                        <el-form-item label="专业:" size="small" label-width="40px">
                            <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                                <el-select v-model="paramsForm.specialties" clearable placeholder="可留空" size="small"
                                    style="width: 150px" multiple collapse-tags collapse-tags-tooltip
                                    @visible-change="getSpecialties" @change="changeSpecialies">
                                    <template #header>
                                        <el-checkbox v-model="specCheckAll" :indeterminate="specIndeterminate"
                                            @change="specHandleCheckAll">
                                            全选
                                        </el-checkbox>
                                    </template>
                                    <el-option v-for="item in specialtiesArr" :label="item.label" :value="item.value"
                                        :key="item.value" />
                                </el-select>
                            </el-config-provider>
                        </el-form-item>
                        <el-form-item label="子系统:" size="small" label-width="65px">
                            <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                                <el-select v-model="paramsForm.subsys" multiple clearable collapse-tags
                                    collapse-tags-tooltip placeholder="可留空" size="small" style="width: 150px"
                                    @change="changeSubsys">
                                    <template #header>
                                        <el-checkbox v-model="subCheckAll" :indeterminate="subIndeterminate"
                                            @change="subHandleCheckAll">
                                            全选
                                        </el-checkbox>
                                    </template>
                                    <el-option v-for="item in subsysArr" :label="item.label" :value="item.value"
                                        :key="item.value" />
                                </el-select>
                            </el-config-provider>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" @click="getMcsRecordCheck(paramsForm)"
                            :loading = "loading">查询</el-button>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control :downloadBoxShow="downloadBoxShow" :permObj="permObj" @showDownload="showDownloadBox"
                @downloadExcelPaging="downloadExcelPaging(newDatasArr, 'checkDateTable', '检测记录与主控记录核对')"
                @downloadExcelAll="downloadExcelAll(datasArr, '检测记录与主控记录核对')"></Control>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage" v-model:pageSize="pageSize" @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)" @toFirst="toFirstPage" @toEnd="toEndPage" @toSpecify="toSpecifyPage"
                @changePsize="changePageSize">
            </Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%" v-loading="loading" id="checkDateTable"
                :span-method="objectSpanMethod">
                <el-table-column fixed prop="WONUM" label="WONUM" width="90" />
                <el-table-column fixed prop="XD" label="描述" width="150" />
                <el-table-column prop="AREA" label="作业区域" width="120" />
                <el-table-column prop="AREA2" label="作业区域2" width="120" />
                <el-table-column prop="ISPASS" label="是否通过" width="60" />
                <el-table-column prop="FINISHDATE" label="实际完成日期" width="120">
                    <template #default="{ row }">
                        {{ dateFormat(row.FINISHDATE) }}
                    </template>
                </el-table-column>
                <el-table-column prop="PERSON" label="配合人" width="80" />
                <el-table-column prop="REMARK" label="备注" width="120" />
                <el-table-column prop="CUST_LINENUM" label="线路" width="60" />
                <el-table-column prop="STA" label="站点" width="120" />
                <el-table-column prop="SPEC_DESC" label="专业名称" width="100" />
                <el-table-column prop="SUB_DESC" label="子系统名称" width="120" />
                <el-table-column prop="PGNAME" label="班组名称" width="130" />
                <el-table-column prop="YEAR" label="计划年度" width="60" />
                <el-table-column prop="DEVICENUM" label="设备编号" width="170" />
                <el-table-column prop="CODE" label="主控设备编号" width="150" />
                <el-table-column prop="REPRESENT" label="主控设备描述" width="180" />
                <el-table-column prop="EVENTTIME" label="事件时间" width="180">
                    <template #default="{ row }">
                        {{ dateFormatTimeStamp(row.EVENTTIME) }}
                    </template>
                </el-table-column>
                <el-table-column prop="STATUS" label="状态" width="120" />
                <el-table-column prop="ACTION" label="事件行为" width="180" />
                <el-table-column prop="STATION" label="车站" width="120" />

            </el-table>
        </template>
    </AdminSkeleton>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue'
import Control from '@/components/Control.vue'
import Paging from '@/components/Paging.vue'
import { xfjcStore } from '@/stores/jcStore'
import { getLinesInfo, getSpecialtiesInfo } from '@/utils/xfjcApi/device'
import { getMcsRecordCheckInfo } from '@/utils/xfjcApi/mcsRecordCheck'
import { msgOpen } from '@/utils/msg'
import { exportClickFromTableId, exportClickFromDatas } from '@/utils/downloadExcel'
import { dateFormatTimeStamp, dateFormat } from '@/utils/dateFormat'
import { paging } from '@/utils/paging'

// import { tableSpanMethod } from '@/utils/tableSpanMethod'

let useJcStore = xfjcStore()

//权限对象--用于控制按钮显示
const permObj = {
    add: { name: 'McsRecordCheck', type: 'add' },
    update: { name: 'McsRecordCheck', type: 'update' },
    delete: { name: 'McsRecordCheck', type: 'delete' }
}

const {
    datasArr,
    datasLength,
    firstPage,
    pageSize,
    countPage,
    newDatasArr,
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页

//参数
//#region 
//线路、站点
let linesAndStationsArr = ref([])
let lineCheckAll = ref(false)
let lineIndeterminate = ref(false) //设置不确定状态，仅负责样式控制
let stationsArr = ref([])
let stationCheckAll = ref(false)
let stationIndeterminate = ref(false)

//专业、子系统
let specialtiesArr = ref([])
let specCheckAll = ref(false)
let specIndeterminate = ref(false)
let subsysArr = ref([])
let subCheckAll = ref(false)
let subIndeterminate = ref(false)

let formRef = ref(null)
//查询表单对象
let paramsForm = reactive({
    begindate: "",
    enddate: "",
    lines: [],
    stations: [],
    specialties: [],
    subsys: [],
    noexists: true,
    description: ''
})

//表单校验
const rules = reactive({
    begindate: [
        { required: true, message: '请选择开始日期', trigger: 'blur' },
    ],
    enddate: [
        { required: true, message: '请选择结束日期', trigger: 'blur' },
    ],
    // line: [
    //     { required: true, message: '请选择线路', trigger: 'blur' },
    // ],
})

let loading = ref(false)

/**
 * location转换为树形
 * @param {Array} arr workType 原数组对象 
 */
const locationToTree = (arr) => {
    let line = []
    // 先把线路拿出来
    arr.forEach(item => {
        if (item.AREATYPE === '线路') {
            let lineObj = {
                label: item.DESCRIPTION,
                value: item.LOCATION,
                children: []
            }
            line.push(lineObj)
        }
    })
    // 再把站点拿出来
    line.forEach(item => {
        arr.forEach(item1 => {
            if (item.value === item1.CUST_LINENUM && item1.AREATYPE !== '线路') {
                let stationObj = {
                    label: item1.DESCRIPTION,
                    value: item1.LOCATION,
                    parent: item.value
                }
                item.children.push(stationObj)
            }
        })
    })
    // console.log(line)
    return line
}

//获取线路站点数据
const getLines = async () => {
    //获取数据
    if (!useJcStore.linesInfo.length) {
        let lines = await getLinesInfo()
        if (lines.status) {
            linesAndStationsArr.value = locationToTree(lines.resDatas.lines)
            useJcStore.setLinesInfo(linesAndStationsArr.value)
        }
    } else {
        linesAndStationsArr.value = useJcStore.linesInfo
    }
}

/**
 * 改变线路联动站点
 * @param val 选中的线路值
 */
const changeLines = (val) => {
    // console.log(val)
    // console.log(typeof val)
    // console.log(Array.isArray(val))    
    //#region  
    //单选   
    if (typeof val === 'string') {
        linesAndStationsArr.value.forEach(item => {
            // console.log(item)            
            if (item.value === val) stationsArr.value = item.children
        })
    }
    //多选 el-select组件多选后使用typeof判断为object，需要使用Array.isArray()才能判断为数组
    if (Array.isArray(val)) {
        //每次改变线路时，都要把站点清空
        paramsForm.stations = []
        stationCheckAll.value = false
        stationIndeterminate.value = false
        if (val.length === 1) {
            //取消全选
            if (linesAndStationsArr.value.length && val.length !== linesAndStationsArr.value.length) {
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            linesAndStationsArr.value.forEach(item => {
                // console.log(item)            
                if (item.value === val[0]) stationsArr.value = item.children
            })
        }
        else if (val.length === 0) {
            stationsArr.value = []
            stationCheckAll.value = false
            stationIndeterminate.value = false
            lineCheckAll.value = false
            lineIndeterminate.value = false
        }
        
        else if (val.length > 1) {
            // 当val长度大于1切等于线路数组长度时，全选勾选
            if (val.length === linesAndStationsArr.value.length) {
                lineCheckAll.value = true
                lineIndeterminate.value = false
            } else {
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            let staArrss = []
            // 当val长度大于1时，获取站点
            for (let i = 0; i < val.length; i++) {
                let staArrs = []
                for (let j = 0; j < linesAndStationsArr.value.length; j++) {
                    let staArr = []
                    if (linesAndStationsArr.value[j].value === val[i]) {
                        staArr.push(...linesAndStationsArr.value[j].children)
                        staArrs.push(...staArr)
                    }
                }
                staArrss.push(...staArrs)
            }
            stationsArr.value = staArrss
        }
    }
    //#endregion
}

// //线路全选
const lineHandleCheckAll = (val) => {
    lineIndeterminate.value = false
    if (val) {
        paramsForm.lines = linesAndStationsArr.value.map((_) => _.value)
        //需要调用changeLines方法，否则会出现选中的线路没有站点的情况
        changeLines(paramsForm.lines)
    } else {
        paramsForm.lines = []
        //需要调用changeLines方法，否则会出现不选线路后站点仍存在的情况
        changeLines(paramsForm.lines)
    }
}

/**
 * 站点变更
 * @param val 选中的站点值
 */
const changeStations = (val) => {
    if (Array.isArray(val)) {
        if (val.length === 1) {
            //取消全选
            if (stationsArr.value.length && val.length !== stationsArr.value.length) {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
        else if (val.length === 0) {
            stationCheckAll.value = false
            stationIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于站点数组长度时，全选勾选
            if (val.length === stationsArr.value.length) {
                stationCheckAll.value = true
                stationIndeterminate.value = false
            } else {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
    }
}

/**
 * 站点全选
 * @param val 站点全选值
 */
const stationHandleCheckAll = (val) => {
    stationIndeterminate.value = false
    if (val) {
        paramsForm.stations = stationsArr.value.map((_) => _.value)
    } else {
        paramsForm.stations = []
    }
}

/**
 * 专业子系统转换为树形
 * @param spec 专业数组
 * @param sub 子系统数组
 */
const specAndSubToTree = (spec, sub) => {
    let specArr = []
    let subs = ['FASFGW', 'FASFSB', 'FASFYG', 'FASMOS', 'GQTSFD', 'FASQSB', 'FASQXF', 'FASXFS', 'FASFHH', 'FASKRQ']
    spec.forEach(item => {
        let specObj = {
            label: item.SPEC_DESC,
            value: item.CUST_SPECNUM,
            children: []
        }
        specArr.push(specObj)
    })
    sub.forEach(item => {
        specArr.forEach(item1 => {
            if (item1.value === item.CUST_SPECNUM && subs.includes(item.CUST_SUBSYS)) {
                let subObj = {
                    label: item.SUB_DESC,
                    value: item.CUST_SUBSYS,
                    parent: item1.value
                }
                item1.children.push(subObj)
            }
        })
    })
    // console.log(specArr)
    return specArr

}

//获取专业及子系统数据
const getSpecialties = async () => {
    if (!useJcStore.rcSpecialtiesInfo.length) {
        //获取专业
        let specAndSub = await getSpecialtiesInfo()
        if (specAndSub.status) {
            specialtiesArr.value = specAndSubToTree(specAndSub.resDatas.specialties, specAndSub.resDatas.subsys)
            useJcStore.setRcSpecialtiesInfo(specialtiesArr.value)
        }
    } else {
        specialtiesArr.value = useJcStore.rcSpecialtiesInfo
    }
}

/**
 * 改变专业联动子系统
 * @param val 选中的专业值
*/

const changeSpecialies = (val) => {
    if (typeof val === 'string') {
        specialtiesArr.value.forEach(item => {
            // console.log(item)
            if (item.value === val) subsysArr.value = item.children
        })
    }
    if (Array.isArray(val)) {
        //每次改变专业时，都要把子系统清空
        paramsForm.subsys = []
        subCheckAll.value = false
        subIndeterminate.value = false
        if (val.length === 1) {
            //取消全选
            if (specialtiesArr.value.length && val.length !== specialtiesArr.value.length) {
                specCheckAll.value = false
                specIndeterminate.value = true
            }
            specialtiesArr.value.forEach(item => {
                // console.log(item)
                if (item.value === val[0]) subsysArr.value = item.children
            })
        }
        else if (val.length === 0) {
            subsysArr.value = []
            subCheckAll.value = false
            subIndeterminate.value = false
            specCheckAll.value = false
            specIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于专业数组长度时，全选勾选
            if (val.length === specialtiesArr.value.length) {
                specCheckAll.value = true
                specIndeterminate.value = false
            } else {
                specCheckAll.value = false
                specIndeterminate.value = true
            }
            let subArrss = []
            // 当val长度大于1时，获取子系统
            for (let i = 0; i < val.length; i++) {
                let subArrs = []
                for (let j = 0; j < specialtiesArr.value.length; j++) {
                    let subArr = []
                    if (specialtiesArr.value[j].value === val[i]) {
                        subArr.push(...specialtiesArr.value[j].children)
                        subArrs.push(...subArr)
                    }
                }
                subArrss.push(...subArrs)
            }
            subsysArr.value = subArrss
        }
    }
}

/**
 * 专业全选
 * @param val 专业全选值
 */
const specHandleCheckAll = (val) => {
    specIndeterminate.value = false
    if (val) {
        paramsForm.specialties = specialtiesArr.value.map((_) => _.value)
        changeSpecialies(paramsForm.specialties)
    } else {
        paramsForm.specialties = []
        changeSpecialies(paramsForm.specialties)
    }
}

/**
 * 子系统变更
 * @param val 选中的子系统值
 */
const changeSubsys = (val) => {
    if (Array.isArray(val)) {
        if (val.length === 1) {
            //取消全选
            if (subsysArr.value.length && val.length !== subsysArr.value.length) {
                subCheckAll.value = false
                subIndeterminate.value = true
            }
        }
        else if (val.length === 0) {
            subCheckAll.value = false
            subIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于子系统数组长度时，全选勾选
            if (val.length === subsysArr.value.length) {
                subCheckAll.value = true
                subIndeterminate.value = false
            } else {
                subCheckAll.value = false
                subIndeterminate.value = true
            }
        }
    }
}

/**
 * 子系统全选
 * @param val 子系统全选值
 */
const subHandleCheckAll = (val) => {
    subIndeterminate.value = false
    if (val) {
        paramsForm.subsys = subsysArr.value.map((_) => _.value)
    } else {
        paramsForm.subsys = []
    }
}
//#endregion

/**
 * 查询对比记录
 * @param form 表单对象
 */
const getMcsRecordCheck = (form) => {
    // console.log(form)
    formRef.value.validate(async (valid) => {
        if (!valid) {
            return false
        } else {
            if (form.begindate > form.enddate) {
                msgOpen("开始日期不能大于结束日期！")
                return false
            }
            loading.value = true
            let res = await getMcsRecordCheckInfo(form)
            // console.log(res)
            pagingPreprocessing(res.resDatas.mcsRecordCheckInfo) //分页前置处理
            // if(res.resDatas.length) tableSpanConfig(newDatasArr.value)
            loading.value = false
        }
    })
}


//下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = () => {
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data, tableId, fileName) => {
    data.length ? exportClickFromTableId(tableId, fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data, fileName) => {
    if (data.length) {
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝        
        exportClickFromDatas(newData, fileName)
    } else {
        msgOpen("无数据可供下载，请先查询数据")
    }
}






//表格行合并
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex <= 15) {
        const cellConfig = spanConfig.value[rowIndex]?.[columnIndex];
        return {
            rowspan: cellConfig?.rowspan || 0,
            colspan: cellConfig?.colspan || 0
        }
    }
}
// 新增计算属性生成合并配置
const spanConfig = ref([])

watch(() => newDatasArr.value, (newData) => {
    const config = []
    const columns = ['WONUM', 'XD', 'AREA', 'AREA2', 'ISPASS', 'FINISHDATE', 'PERSON', 'REMARK',
        'CUST_LINENUM', 'STA', 'SPEC_DESC', 'SUB_DESC', 'PGNAME', 'YEAR', 'DEVICENUM', 'SBDESC']
    const prevRowColName = ref([])
    columns.map(item => {
        const obj = { [item]: "" }
        prevRowColName.value.push(obj)
    })
    // const prevRowColName = ref([
    //     { WONUM: "", prevCount: 0, prevBigger: 0, },
    //     { XD: "", prevCount: 0, prevBigger: 0, },
    //     { AREA: "", prevCount: 0, prevBigger: 0, },
    //     { AREA2: "", prevCount: 0, prevBigger: 0, },
    //     { ISPASS: "", prevCount: 0, prevBigger: 0, },
    //     { FINISHDATE: "", prevCount: 0, prevBigger: 0, },
    //     { PERSON: "", prevCount: 0, prevBigger: 0, },
    //     { REMARK: "", prevCount: 0, prevBigger: 0, },
    //     { CUST_LINENUM: "", prevCount: 0, prevBigger: 0, },
    //     { STA: "", prevCount: 0, prevBigger: 0, },
    //     { SPEC_DESC: "", prevCount: 0, prevBigger: 0, },
    //     { SUB_DESC: "", prevCount: 0, prevBigger: 0, },
    //     { PGNAME: "", prevCount: 0, prevBigger: 0, },
    //     { YEAR: "", prevCount: 0, prevBigger: 0, },
    //     { DEVICENUM: "", prevCount: 0, prevBigger: 0, },
    //     { SBDESC: "", prevCount: 0, prevBigger: 0, },
    // ])

    newData?.forEach((row, idx) => {
        config[idx] = {}
        columns.forEach((colname, cidx) => {
            //如果当前行的当前列的值不等于上一行的当前列的值
            if (row[colname] !== prevRowColName.value[cidx][colname]) {
                let count = 1 //当前行的合并数  
                for (let i = idx + 1; i < newData.length; i++) {
                    if (newData[i][colname] === row[colname]) {
                        count++
                    } else break
                }
                config[idx][cidx] = { rowspan: count, colspan: 1 }
                prevRowColName.value[cidx][colname] = row[colname]
            } else {
                config[idx][cidx] = { rowspan: 0, colspan: 1 }
            }
            //console.log(prevRowColName.value[cidx])
        })
    })
    spanConfig.value = config
    // console.log(spanConfig.value)
}, { immediate: true })


</script>

<style lang="less" scoped>
.params-form {
    height: 100%;
    width: 100%;

    .el-form {
        height: 100%;
        width: 100%;

        .one-box,
        .two-box {
            height: 50%;
            width: 100%;
            display: flex;
            justify-content: flex-start;
            align-items: center;

            .el-form-item {
                margin-bottom: 0;
                margin-right: .3125rem;
            }
        }
    }
}

.el-table {
    height: 95%;
}
</style>